package com.lalosoft.gastostarjetaweb.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.JSONObject;
import com.lalosoft.gastostarjetaweb.dao.ItemDao;
import com.lalosoft.gastostarjetaweb.model.Item;

@SuppressWarnings(value="serial")
public class AgregarItemServlet extends HttpServlet {
	
	private static final Logger log = Logger.getLogger("AgregarItemServlet");

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		String data = req.getParameter("data");
		String uuidUser = req.getParameter("token");
		try {
			JSONObject json = new JSONObject(data);
			Item item = new Item();
			item.setUserUuid(uuidUser);
			item.setCantidadCuotas(json.getString("cantidadCuotas"));
			item.setCuotasRestantes(json.getString("cuotasRestantes"));
			item.setDetalle(json.getString("detalle"));
			item.setFechaCompra(json.getString("fechaCompra"));
			item.setValorCuota(json.getString("valorCuota"));
			
			Long itemId = ItemDao.save(item);
			log.log(Level.WARNING, "Nuevo item guardado - Id: " + itemId);
			
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("itemId", itemId);
			log.log(Level.WARNING, "JsonEnviado: " + jsonObject.toString());
			resp.setContentType("application/json");
			// Get the printwriter object from response to write the required json object to the output stream      
			PrintWriter out = resp.getWriter();
			// Assuming your json object is **jsonObject**, perform the following, it will return your json object  
			out.print(jsonObject);
			out.flush();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	
}
